<script setup>
import * as THREE from 'three';
import { onMounted, onUnmounted, ref } from 'vue';
import { Box3, BoxHelper, PlaneHelper, Plane, AxesHelper } from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const container = ref(null);
let scene, renderer, camera, controls, handleResize;

onMounted(() => {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x87CEEB); // 设置背景颜色为浅蓝色

  // 创建相机
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 10;

  // 创建渲染器
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.value.appendChild(renderer.domElement);

  // 窗口resize事件处理
  handleResize = () => {
    const { clientWidth, clientHeight } = container.value;
    console.log('resize',clientWidth,clientHeight);
    camera.aspect = clientWidth / clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(clientWidth, clientHeight);
  };

  // 初始化时立即执行一次

  window.addEventListener('resize', handleResize);
  handleResize();

  // 创建几何体
  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  // 创建边界框
  const box = new Box3().setFromObject(cube);
  const boxHelper = new BoxHelper(cube, 0xffff00);
  scene.add(boxHelper);

  // 创建光源
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(ambientLight);
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
  directionalLight.position.set(1, 1, 1);
  scene.add(directionalLight);

  // 创建 PlaneHelper
  const plane = new Plane(new THREE.Vector3(0, 1, 0), -5);
  const planeHelper = new PlaneHelper(plane, 10, 0xffff00);
  scene.add(planeHelper);

  // 创建 AxesHelper
  const axesHelper = new AxesHelper(5); // 参数 5 表示坐标轴的长度
  scene.add(axesHelper);
  const controls = new OrbitControls(camera, renderer.domElement);
  // 渲染循环
  const animate = () => {
    requestAnimationFrame(animate);

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    boxHelper.update();
    renderer.render(scene, camera);
    controls.update();
  };

  animate();
});

onUnmounted(() => {
  // 清理资源
  const containerElement = container.value;
  if (containerElement) {
    while (containerElement.firstChild) {
      containerElement.removeChild(containerElement.firstChild);
    }
  }
  window.removeEventListener('resize', handleResize);
  if (renderer) renderer.dispose();
  if (scene) scene.remove.apply(scene, scene.children);
});
</script>

<template>
  <div ref="container"></div>
</template>

<style scoped>
  div {
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
    /* overflow: hidden; */
  }
</style>